/*
 * @Author: wwssaabb
 * @Date: 2021-12-11 15:35:38
 * @LastEditTime: 2021-12-11 17:54:14
 * @FilePath: \handwritten-code\array\forEach.js
 */

//实现Array.prototype.forEach()，接收一个执行函数并向里面传参item、index、array，thisArg

Array.prototype.MyForEach = function (executor, thisArg = globalThis) {
  //this判断
  if (this == null) return new TypeError('this is null or undefined')
  //回调函数判断类型判断
  if (typeof executor !== 'function') return new TypeError(executor + ' is no a function')

  let arr = this //这里的this执行调用方法的数组
  for (let i = 0; i < arr.length; i++) {
    executor.call(thisArg, arr[i], i, arr)
  }
}

let arr = [1, 2, 3, 4, 5, 6]
let arr1 = []

let a = {
  name: '三金'
}
// arr.forEach(i => console.log(i ** 2), a)
// arr.MyForEach(i => console.log(i ** 2), a)
arr1.forEach(i => console.log(i ** 2 + this.name), a)
arr1.MyForEach(i => console.log(i ** 2 + this.name), a)